<template>
  <div>
    <div class="activity_table" style="margin-top:0px;margin-left: 0px">
    <el-table :data="user_activities" style="width: 100%">
      <el-table-column prop="user.account" label="用户账号" width="150"></el-table-column>
      <el-table-column label="活动详情">
        <template slot-scope="scope">
          <el-table :data="scope.row.activities" style="width: 100%">
            <el-table-column label="活动名称" prop="name" width="200"></el-table-column>
            <el-table-column label="审核状态" width="120">
              <template slot-scope="innerScope">
                <span>{{ getActivityStatus(innerScope.row.registrationStatus) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="详情" width="100">
              <template slot-scope="innerScope">
                <el-button
                    size="mini"
                    @click="showDetail(innerScope.row)"
                >
                  活动详情
                </el-button>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
              <template slot-scope="innerScope">
                <el-button
                    v-if="[2, 3, 4].includes(innerScope.row.registrationStatus)"
                    size="mini"
                    type="success"
                    @click="approveActivity(scope.row.user.id, innerScope.row.id)"
                >
                  通过
                </el-button>
                <el-button
                    v-if="[2, 3, 4].includes(innerScope.row.registrationStatus)"
                    size="mini"
                    type="danger"
                    @click="rejectActivity(scope.row.user.id, innerScope.row.id)"
                >
                  不通过
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>
      <el-table-column label="用户信息" width="200">
        <template slot-scope="scope">
        <el-button @click="showUserDetails(scope.row.user)">用户详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    </div>
    <el-dialog
        title="报名人员"
        :visible.sync="userVisible"
        width="50%"
    >
      <el-table :data="[user]" style="width: 100%">
<!--        <el-table-column type="index" label="序号"></el-table-column>-->
        <el-table-column label="账号" prop="account"></el-table-column>
        <el-table-column label="年龄" prop="age"></el-table-column>
        <el-table-column label="手机号" prop="phone"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="角色" >{{getRoleName(user.role)}}</el-table-column>
        <el-table-column label="省份" prop="province"></el-table-column>
        <el-table-column label="城市" prop="city"></el-table-column>
        <el-table-column label="成绩" prop="grade"></el-table-column>
      </el-table>
    </el-dialog>
    <el-dialog
        :visible="dialogVisible"
        title="活动详情"
        :show-close="false"
    >
      <span>活动详情：</span>
      <p v-html="detail"></p>
      <img v-if="imageUrl" :src="imageUrl" alt="活动图片" style="max-width: 100%; height: auto;" />
      <el-button @click="downloadFile" v-if="imageUrl">下载图片</el-button>
      <el-button type="primary" @click="closeDialog">关闭</el-button>
    </el-dialog>
  </div>
</template>

<script>
import {getCheckStudent, checkPassStudent, checkNotPassStudent, queryRegistrationStatus} from '../../../../api/check'

import {mapGetters} from 'vuex'
import {getActivityByUid, getDetail} from '../../../../api/activity'
import {getActivityUrl} from '../../../../api/activityUrl'
import {getUserByAccount} from '../../../../api/user'
import {downloadFile} from '../../../../api/api'
export default {
  inject: ['reload'],
  computed: {
    ...mapGetters({
      userRole: 'user/getUserRole',
      userAccount: 'user/getUserAccount',
      userId: 'user/getUserId'
    })
  },
  data () {
    return {
      detail: '',
      imageUrl: '',
      dialogVisible: false,
      user: [],
      activities: [],
      user_activities: [],
      userVisible: false
    }
  },
  created () {
    this.fetchActivities()
  },
  methods: {
    closeDialog () {
      this.dialogVisible = false
    },
    downloadFile () {
      getActivityUrl(this.activityId).then(urlResult => {
        console.log(urlResult)
        let obj = {
          path: urlResult[0].url
        }
        downloadFile(obj)
          .then(response => {
            // 通过创建 Blob 对象来处理下载的文件
            const blob = new Blob([response], { type: 'image/jpeg' })

            // 创建一个 URL，用于文件下载
            const downloadUrl = window.URL.createObjectURL(blob)

            // 创建一个 <a> 标签来触发下载
            const link = document.createElement('a')
            link.href = downloadUrl
            link.download = decodeURIComponent(urlResult[0].fileName)
            link.style.display = 'none'

            document.body.appendChild(link)
            link.click()

            // 清理资源
            window.URL.revokeObjectURL(downloadUrl)
            document.body.removeChild(link)
          })
          .catch(error => {
            console.error(error)
            // 处理错误
          })
      })
    },
    showDetail (activity) {
      Promise.all([getDetail(activity.id), getActivityUrl(activity.id)])
        .then(([detailResult, urlResult]) => {
          this.activityId = activity.id
          this.detail = detailResult.activityDescription
          this.imageUrl = urlResult[0].url // 获取第一个对象的 URL 属性
          this.dialogVisible = true
        })
        .catch(error => {
          // 处理错误
          console.error(error)
          this.$message.error('获取活动详情或链接时出错')
        })
    },
    getRoleName (role) {
      if (role === 1) {
        return '学生'
      } else if (role === 2) {
        return '老师'
      } else if (role === 3) {
        return '学院'
      } else if (role === 4) {
        return '学校'
      } else {
        return '其他'
      }
    },
    getActivityStatus (registration) {
      // 根据 registration 的值返回对应的审批状态
      if (registration === 2) {
        return '未审核'
      } else if (registration === 3) {
        return '审批通过'
      } else if (registration === 4) {
        return '审批不通过'
      } else {
        return '其他状态'
      }
    },
    fetchActivities () {
      const uid = this.userId
      getCheckStudent(uid)
        .then(users => {
          this.users = users
          const userPromises = []

          for (const user of this.users) {
            userPromises.push(
              getActivityByUid(user.id)
                .then(activities => {
                  const activityPromises = activities.map(activity => {
                    return queryRegistrationStatus(user.id, activity.id)
                      .then(status => {
                        activity.registrationStatus = status
                        return activity
                      })
                  })
                  return Promise.all(activityPromises)
                    .then(activitiesWithStatus => {
                      return {
                        user: user,
                        activities: activitiesWithStatus
                      }
                    })
                })
            )
          }
          Promise.all(userPromises)
            .then(userActivityList => {
              this.user_activities = userActivityList
              console.log(this.user_activities)
            })
        })
        .catch(error => {
          console.error('Error fetching activities:', error)
        })
    },
    showUserDetails (user) {
      console.log(user)
      getUserByAccount(user.account).then(result => {
        this.user = result
      })
      this.userVisible = true
    },
    approveActivity (uid, aid) {
      // 调用审核通过的后端接口方法
      checkPassStudent(uid, aid)
        .then(response => {
          this.fetchActivities() // 重新加载活动列表
        })
        .catch(error => {
          console.error('Error approving activity:', error)
        })
    },
    rejectActivity (uid, aid) {
      // 调用审核不通过的后端接口方法
      checkNotPassStudent(uid, aid)
        .then(response => {
          this.fetchActivities() // 重新加载活动列表
        })
        .catch(error => {
          console.error('Error rejecting activity:', error)
        })
    }
  }
}
</script>
<style scoped>
/*最外层透明*/
/deep/ .el-table, /deep/ .el-table__expanded-cell{
  background-color: transparent;
}
/* 表格内背景颜色 */
/deep/ .el-table th,
/deep/ .el-table tr,
/deep/ .el-table td {
  background-color: transparent;
}
/deep/ .el-table__header{
  background-color: transparent;
}
.el-table th.el-table__cell{
  background-color: transparent;
}
.el-table__header{
  background-color: transparent;
}
/*.activity_table /deep/  .el-table, .el-table__expanded-cell,el-table-column {*/
/*  background-color: transparent;*/
/*}*/
/*.activity_table /deep/ .el-table tr,el-table-column {*/
/*  background-color: transparent!important;*/
/*}*/
/*.activity_table /deep/  .el-table--enable-row-transition .el-table__body td, .el-table .cell,el-table-column{*/
/*  background-color: transparent;*/
/*}*/
</style>
